package com.swb.mybatis04emp.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;

/**
 * @title: MyBatisUtils
 * @author: 流沐颖
 * @date:2022/6/4 11:01
 * @description:
 * @version: study
 */
public class MyBatisUtils {
    private static SqlSessionFactory factory;
    /**
     * 本地线程
     */
    private static ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();


    /**
     *
     * 静态代码块进行初始化
     */
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis_config.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接
     */
    public static SqlSession getConn() {
        SqlSession session = THREAD_LOCAL.get();
        if (session == null) {
            // 调用工厂生成连接
            session = factory.openSession();
            // 将连接对象放在线程池中
            THREAD_LOCAL.set(session);
        }
        return session;
    }


    /**
     * 提交事务
     */
    public static void commit() {
        // 调用方法进行提交
        SqlSession conn = getConn();
        conn.commit();
        //close();
    }

    /**
     *  回滚事务
     */
    public static void rollback() {
        // 调用方法进行提交
        SqlSession conn = getConn();
        conn.rollback();
        //close();
    }

    /**
     * 关闭连接对象
     */
    public static void  close(){
        SqlSession conn = getConn();
        conn.close();
        // 也要从本地线程池中将连接对象移除
        THREAD_LOCAL.remove();

    }


    /**
     * 得到dao接口的实现类对象
     */
    public static <T> T getMapper(Class<T> clazz){
        SqlSession conn = getConn();
        return conn.getMapper(clazz);
    }


}
